#-*- coding:utf-8 -*-
from django.http import HttpResponse
from datetime import datetime
from userinfo.models import Userinfo
from ifoundyou.models import Coordinate, CoordinateTimes
from django.shortcuts import render_to_response
from Graduation_web.settings import IFOUNDYOU_BODY_VALUE,IFOUNDYOU_BTN_VALUE,IFOUNDYOU_TITLE_VALUE
from Graduation_web.views import get_msg_count

def ifoundyou_by_time(request):
    sign = 'ifoundyou'
    if request.method == 'GET':
        username = request.session.get('user','')
        msg_count = get_msg_count(username)
        index_time = request.GET.get('index_time','')
        telephone = request.GET.get('telephone','')
        if not index_time or not telephone:
            error_ms = '出错了'
            return render_to_response('erro.html',locals())
        else:
            coordinates = Coordinate.objects.filter(telephone = telephone).order_by('-now_time')
            try:
                get_coordinate = Coordinate.objects.get(telephone = telephone,now_time = index_time)
                coordinatetimes = CoordinateTimes.objects.filter(times = get_coordinate.times)
            except:
                erro_msg = '对象出错了'
                return render_to_response('erro.html',locals())
            type,longitude,latitude,t_time = get_map_src(coordinatetimes)
            return render_to_response('ifoundyou_res.html',locals())

def ifoundyou_by_phone(request):
    sign = 'ifoundyou'
    username = request.session.get('user','')
    msg_count = get_msg_count(username)
    title = IFOUNDYOU_TITLE_VALUE
    btn = IFOUNDYOU_BTN_VALUE
    body = IFOUNDYOU_BODY_VALUE
    if request.method == 'POST':
        telephone = request.POST.get('telephone','')
        if telephone.startswith('+86'):
            telephone = telephone[3:]
        elif telephone.startswith('0086'):
            telephone = telephone[4:]
        elif len(telephone) != 11 or telephone[0] != '1':
            error = '手机号码错误！'
            return render_to_response('ifoundyou.html',locals())
        try:
            int(telephone)
        except:
            error = '手机号码错误！'
            return render_to_response('ifoundyou.html',locals())
        coordinates = Coordinate.objects.filter(telephone = telephone).order_by('-now_time')
        if len(coordinates) == 0:
            empty = True
        else:
            index_time = coordinates[0].now_time
        coordinatetimes = CoordinateTimes.objects.filter(times = coordinates[0].times)
        type,longitude,latitude,t_time = get_map_src(coordinatetimes)
        return render_to_response('ifoundyou_res.html',locals())
    
def ifoundyou_action(request):
    sign = 'ifoundyou'
    username = request.session.get('user','')
    msg_count = get_msg_count(username)
    title = IFOUNDYOU_TITLE_VALUE
    btn = IFOUNDYOU_BTN_VALUE
    body = IFOUNDYOU_BODY_VALUE
    return render_to_response('ifoundyou.html',locals())

def getcoordinate_action(request):
    username = request.GET.get('username',0)
    telephone = request.GET.get('telephone',0)
    times = request.GET.get('times',0)
    longitude = request.GET.get('longitude',0)
    latitude = request.GET.get('latitude',0)
    
    if not username or not telephone or not times or not longitude or not latitude:
        return HttpResponse('parameter error')
    else:
        try:
            Userinfo.objects.get(username=username)
        except:
            return HttpResponse("user doesn't exist")
        if telephone.startswith('+86'):
            telephone = telephone[3:]
        elif telephone.startswith('0086'):
            telephone = telephone[4:]
        elif telephone[0] != '1':
            return HttpResponse('telephone error')
        try:
            int(telephone)
        except:
            return HttpResponse('telephone error just num')
        try:
            float(longitude)
            float(latitude)
        except:
            return HttpResponse('longitude or latitude is error')
        user = Userinfo.objects.get(username = username)
        try:
            coordinate = Coordinate.objects.get(username = username,telephone = telephone,times = '%s%s' % (username,times))
        except:
            coordinate = Coordinate(username = user,telephone = telephone,times = '%s%s' % (username,times),now_time = str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
            coordinate.save()
        coordinateTimes = CoordinateTimes(times = coordinate,current_time = datetime.now(),longitude = longitude,latitude = latitude)
        coordinateTimes.save()
        return HttpResponse('success')
    
def get_map_src(objs):
    left = 180.0
    right = -180.0
    up = -90.0
    down = 90.0
    for obj in objs:
        if float(obj.longitude) > right:
            right = float(obj.longitude)
        if float(obj.longitude) < left:
            left = float(obj.longitude)
        if float(obj.latitude) > up:
            up = float(obj.latitude)
        if float(obj.latitude) < down:
            down = float(obj.latitude)
    left = left - 100
    right = right + 100
    up = up +100
    down = down -100
    if len(objs) == 1:
        return (1,objs[0].longitude,objs[0].latitude,objs[0].current_time)
    else:
        return (2,(left + (right-left)/2),(down+(up-down)/2),0)
    